# # -*- coding:utf-8 -*-
import django
import os, time

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "server.settings")
django.setup()
import logging
from random import Random

from conf.sysConfig import config
from software.models import SoftwareVersion
from order.models import SoftwareOrder
from user.dataCheck import DataCheck
from user.models import User, FileStore

datacheck = DataCheck()
tmpDir = os.path.join(config["dataDir"], config["tmpDir"])
logger_request = logging.getLogger("django.request")


def createOrder(softwareVersionId, userId, deliveryType='', orderType='0', groupId=0, softFileId=""):
    softwareVersion = SoftwareVersion.objects.filter(pk=softwareVersionId)
    softwareVersionItem = softwareVersion[0]
    user = User.objects.filter(pk=userId)
    userItem = user[0]

    if not softFileId == "":
        softFileList = FileStore.objects.filter(pk=softFileId)
        if softFileList.exists():
            softFile = softFileList[0]
        else:
            softFile = None
    else:
        softFile = None

    if deliveryType == '3':
        orderState = '2'
        examineState = '1'
        isExamine = True
        isDownLoad = True
    else:
        orderState = '0'
        examineState = '0'
        isExamine = False
        isDownLoad = False
    if groupId == 0:

        order = SoftwareOrder.objects.create(
            softwareVersion=softwareVersionItem,
            user=userItem,
            delieverType=softwareVersionItem.deliveryType,
            orderNumber=orderNum(),
            orderState=orderState,
            examineState=examineState,
            isExamine=isExamine,
            isDownload=isDownLoad,
            orderType=orderType,
            softFile=softFile
        )
    else:
        order = SoftwareOrder.objects.create(
            softwareVersion=softwareVersionItem,
            user=userItem,
            delieverType=softwareVersionItem.deliveryType,
            orderNumber=orderNum(),
            orderState=orderState,
            examineState=examineState,
            isExamine=isExamine,
            orderType=orderType,
            group_id=groupId,
            isDownload=isDownLoad,
            softFile=softFile
        )


def random_str(randomlength=16):
    """
    生成随机字符串
    :param randomlength: 字符串长度
    :return:
    """
    strs = ''
    chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'
    length = len(chars) - 1
    random = Random()
    for i in range(randomlength):
        strs += chars[random.randint(0, length)]
    return strs


def orderNum():
    timeStamp = time.time()
    localTime = time.localtime(timeStamp)
    strTime = time.strftime("%Y%m%d%H%M%S", localTime)
    num = strTime + random_str(2)
    return num

# if __name__ == '__main__':
#     createOrder(softwareVersionId=47, userId=5, deliveryType='', orderType='0')
# orderNum()
